package com.example.alphabetindexer.demo;

import java.util.List;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.example.alphabetindexer.R;
import com.example.alphabetindexer.util.Log;
import com.example.alphabetindexer.util.StringTools;
import com.example.alphabetindexer.util.UIHelp;
import com.example.alphabetindexer.widget.AlphabetIndexerActivity;
import com.example.alphabetindexer.widget.AlphabetIndexerBean;

public class ContactActivity extends AlphabetIndexerActivity {
	private List<AlphabetIndexerBean> contactList;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_contact);

		super.initView();
		contactList = super.getList();  // 获取父类的list对象引用

		new GetContactTask().execute();
		
		// atearsan/2013-08-07 item 事件监听
		itemListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Contact contact = null;
				// 如果是搜索模式, 取值要从beanFilterList里取
				if(inSearchMode && getBeanFilterList().size() > 0) {
					contact = (Contact) getBeanFilterList().get(position);
				} else {
					contact = (Contact) contactList.get(position);
				}
				
				Toast.makeText(ContactActivity.this, contact.getName()+" clicked...", Toast.LENGTH_SHORT).show();
				Log.d("contact.toString():"+contact.toString());
			}
		});
	}

	private void updateListViewAdapter() {
		if (adapter == null) {
			super.onBeanListPrepared(new ContactAdapter(this, contactList)); // list数据准备好
		} else {
			adapter.setBeanList(contactList);
			adapter.notifyDataSetChanged();
		}
	}

	class GetContactTask extends AsyncTask<Integer, Integer, String> {
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			UIHelp.showLoading(ContactActivity.this, "获取通讯录...");
		}
		
		@Override
		protected String doInBackground(Integer... params) {
			long m11 = System.currentTimeMillis();
			contactList.clear();
			
			// 第二个执行方法,onPreExecute()执行完后执行
			ContentResolver cr = getContentResolver();
			Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);

			// 一个人可能有几个号码
			// @Xiewenjun
			while (phone.moveToNext()) {
				String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				/**
				 * 对phonenum全字符做空格处理, 替换成空字符(HUAWEI自带系统的电话号码是134 5678 1234这样的格式, 无法发送短信)
				 * @author ChenRen/2013-08-01
				 */
				if(StringTools.isNotEmpty(phoneNumber)) {
					phoneNumber = phoneNumber.replaceAll("\\s|\\+86", StringTools.EMPTY);
				}
				
				String name = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
				String contactId = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
				Contact contact = new Contact(name, phoneNumber);
				if(StringTools.isNotEmpty(contactId)) {
					contact.setId(Integer.parseInt(contactId));
				}
				
				contact.setFirstPhone(phone.isFirst());
				/**
				 * sortKey做首字符处理: 1. 首字符去空格; 2. 如果是非英文, 替换成#<br>
				 * (主要针对邀请成员: 成员的数据是服务器数据, 没有sortkey, 所以要转成符合手迹通讯录里面数据格式的数据.
				 *  因为部分成员的名称前有空格, 转成拼音保存sortkey, 取值的时候要替换掉首字符空格, 而且要把非英文字符替换成#才符合手机通讯录里的数据格式)
				 * @author ChenRen/2013-08-01
				 */
				String sortKey = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY));
				if(StringTools.isNotEmpty(sortKey) && sortKey.trim().length() > 0) {
					String firstChar = sortKey.trim().charAt(0)+StringTools.EMPTY;
					if (firstChar.matches("[^A-Za-z]")) {
						sortKey = "#" + sortKey;
					}
					contact.setSortKey(sortKey.toUpperCase());
				}
				
				contactList.add(contact);
//					Log.d(contact.toString());
//					Log.d("contactList.size():"+contactList.size());
			}
			// End 2013-7-6
			phone.close();

			long m22 = System.currentTimeMillis();
			Log.d("读取手机联系人耗时(s): "+(m22-m11)/1000);
			
			return StringTools.EMPTY;
		}

		@Override
		protected void onPostExecute(String result) {
			updateListViewAdapter();
			UIHelp.closeLoading();
			super.onPostExecute(result);
		}

	}

}
